// local setup
$(function () {
    var all_controls = $('.form-control'), server = $('#server'), btn_ok = $('.btn-ok'),
        custom_switch = $('.custom-switch');
    $(window).on ('resize', function () {
        var toolbar = $('.tool-bar'), top = toolbar.offset ().top + toolbar.height (), H = $(window).height ();
        $('.root-container').css ({height:H-top});
    }).trigger ('resize');

    btn_ok.on ('click', function () {
        if ($(this).hasClass ('disabled')) {
            return;
        }
        var tunnel = global.tunnel || {}, param, proxy;
        tunnel.name = $('#tunnel-name').val ();
        tunnel.service_port = $('#mapping-port').val ();
        tunnel.peer = $('#local-server').val ();
        tunnel.peer_port = $('#local-service-port').val ();
        tunnel.server = server.val ();
        tunnel.status = custom_switch.is (':checked') ? 'on' : 'off';

        console.log ('server - ' + server.val ());

        param = JSON.stringify (tunnel);
        console.log ('tunnel - ' + param);
        proxy = bridge.require ('save', param);
        if (proxy) {
            global.tunnel = proxy;
            change_button_state (global.tunnel);
        } else {
            console.error ('save tunnel[' + tunnel.name + '] failed.');
        }
    });
    $('.remove-button').on ('click', function () {
        if ($(this).hasClass ('disabled')) {
            return;
        }

        $.Alert.warn (RS (R, 'tunnel.message.confirm-delete', {name:global.tunnel.name}), 'after-close', function () {
            var ret = bridge.require ('delete', global.tunnel.id);
            if (!ret) {
                console.error ('remove tunnel failed.');
            } else {
                console.log ('remove tunnel success.');
                $.Alert.info ('remove tunnel success', 'after-close', function () {
                    bridge.require ('force-close', '');
                });
            }
        });
    });

    $('.number-field').on ('keydown', port_checker);
    all_controls.on ('keyup', check_toolbar_state);

    server.on ('change', check_toolbar_state);
    custom_switch.on ('change', check_toolbar_state);
/*    
    $('#tunnel-name').on ('blur', function () {
        if (this.value != '') {
            var o = bridge.require ('check-tunnel-name', this.value);
            console.log ('o = ' + o);
            if (!o) {
                console.error ('check tunnel fail');
                $(this).addClass ('error-box');
            }
        }
    }).on ('focus', function () {
        $(this).removeClass ('error-box');
    });
*/

    function check_toolbar_state () {
        var dirty = !('tunnel' in global), i, status;
        for (i = 0; i < all_controls.length; i ++) {
            if (all_controls [i].value === '') {
                btn_ok.addClass ('disabled');
                return;
            }

            if (!dirty) {
                switch (this.id) {
                    case 'mapping-port':
                        if (this.id == all_controls[i].id && global.tunnel.service_port != all_controls [i].value) {
                            dirty = true;
                        }
                        break;

                    case 'local-server':
                        if (this.id == all_controls[i].id && global.tunnel.peer != all_controls [i].value) {
                            dirty = true;
                        }
                        break;

                    case 'local-service-port':
                        if (this.id == all_controls[i].id && global.tunnel.peer_port != all_controls [i].value) {
                            dirty = true;
                        }
                        break;
                }
            }
        }

        if (server[0].selectedIndex <= 0) {
            btn_ok.addClass ('disabled');
            return;
        }

        if (!dirty) {
            if (server.val () !== global.tunnel.server) {
                dirty = true;
            } else {
                status = $('.custom-switch').is (':checked') ? 'on' : 'off';
                if (status != global.tunnel.status) {
                    dirty = true;
                }
            }
        }

        if (dirty) {
            btn_ok.removeClass ('disabled');
        } else {
            btn_ok.addClass ('disabled');
        }
    }
});

var global = {};

function update_ui () {
    var locale = window.LOCALE || 'en_US',
        res    = R [locale] || R ['en_US'],
        k, c, f;
    console.log ('current locale = ' + locale);
    res = res.tunnel.labels;
    for (k in res) if (res.hasOwnProperty (k)) {
        if (k.startsWith ('btn-')) {
            $('.' + k).attr ('title', res [k]);
        } else if (k.startsWith ('lbl-')) {
            c = $('#' + k).text (res [k]);
            f = c.attr ('for');
            if (f) {
                $('#' + f).attr ('placeholder', res[k]);
            }
        }
    }
}

function on_page_load (data) {
    var server = $('#server'), i;
    if (typeof data === 'string') {
        data = eval ('(' + data + ')');
    }

    if (('servers' in data) && data.servers.length) {
        for (i = 0; i < data.servers.length; i ++) {
            $('<option />').attr ('value', data.servers[i]).text (data.servers[i]).appendTo (server);
        }
    }

    if ('tunnel' in data) {
        global.tunnel = data.tunnel;
        $('#tunnel-name').val (data.tunnel.name).attr ('readonly', 'readonly');
        $('#mapping-port').val (data.tunnel.service_port);
        $('#local-server').val (data.tunnel.peer);
        $('#local-service-port').val (data.tunnel.peer_port);
        server.val (data.tunnel.server);

        if (data.tunnel.status === 'on') {
            $('.custom-switch').customSwitch ('on');
        } else {
            $('.custom-switch').customSwitch ('off');
        }

        change_button_state (global.tunnel);
        $('.btn-ok').addClass ('disabled');
    } else {
        $('.btn-ok').removeClass ('disabled');
    }
    server.selectpicker ();
}

function change_button_state (proxy) {
    if (!proxy) {
        return;
    }

    if (proxy.id) {
        $('.btn-remove').removeClass ('disabled');
    }

    if (proxy.connected) {
        $('.btn-connected').addClass ('disabled');
        $('.btn-disconnected').removeClass ('disabled');
    } else {
        $('.btn-connected').removeClass ('disabled');
        $('.btn-disconnected').addClass ('disabled');
    }
}